package com.byxy.ssm.demo.realm;

import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.byxy.ssm.demo.entity.User;
import com.byxy.ssm.demo.service.UserService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class MyRealm extends AuthorizingRealm {

	@Autowired
	private UserService userService;

	/**
	 * 权限安全，本地 缓存Ehcache  缓存服务redis
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		User u = (User)principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		Set<String> stringPermissions = new HashSet<>();
		stringPermissions.add("user:create");
		stringPermissions.add("user:delete");
		stringPermissions.add("user:update");
		authorizationInfo.setStringPermissions(stringPermissions );
		
		Set<String> roles = new HashSet<>();
		roles.add("super");
		authorizationInfo.setRoles(roles);
		return authorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		
		String userName = (String)token.getPrincipal();
		User user = userService.loginByName(userName);
		if (user != null)
			return new SimpleAuthenticationInfo(user, user.getUserPassword(), this.getName());
		return null;
		 
		// TODO Auto-generated method stub
		
				//UsernamePasswordToken tk = (UsernamePasswordToken) token;
				//log.info("token = " + tk.getUsername());
				//log.info("token = " + new String(tk.getPassword()));
				// User user = userService.login(tk.getUsername(), new
				// String(tk.getPassword()));
	}

}
